package com.example.my_rabbitmq_high_demo.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: Confirm消息确认模式消费者
 * @Author: GaoJian
 * @Date: 2022/7/6 21:50
 */
public class ConsumerByConfirm {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1、创建连接工厂并设置属性
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/");

        //2、创建连接
        Connection connection = factory.newConnection();

        //3、创建channel
        Channel channel = connection.createChannel();

        //4、声明exchange
        String exchangeName = "test_confirm_exchange";
        String exchangeType = "topic";
        String routingKey = "confirm.*";
        channel.exchangeDeclare(exchangeName, exchangeType, true, false, null);

        //5、声明消息队列
        String queueName = "test_confirm_queue";
        channel.queueDeclare(queueName, true, false, false, null);

        //6、绑定队列和交换机
        channel.queueBind(queueName, exchangeName, routingKey);

        //7、创建一个消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);

        //8、设置消费者从哪个队列开始消费，设置自动ACK
        channel.basicConsume(queueName, true, consumer);

        //9、消费
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println(msg);
        }
    }
}
